package csc.fresher.finalgroupfour.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import csc.fresher.finalgroupfour.domain.Customer;

/**
 * @author CSCADMIN
 *
 */
@Repository("customerDAO")
public class CustomerDAO {
	
	@PersistenceContext
	private EntityManager em; // Entity Manager is acquired by container.
	
	/** 
	 * Add a new customer.
	 * @param customer
	 */
	@Transactional
	public void addCustomer(Customer customer) {
		em.persist(customer);
	}
	
	/** 
	 * List all customers in database.
	 * @return
	 */
	@Transactional
	public List<Customer> listCustomers() {
		List<Customer> customers = new ArrayList<Customer>();
		TypedQuery<Customer> query = em.createQuery("SELECT a FROM Customer a", Customer.class);
		
		customers = query.getResultList();
		if (customers.size() > 0) {
			return customers;
		}
		return null;
	}
	
	/** 
	 * List available customers in database.
	 * @return
	 */
	@Transactional
	public List<Customer> listAvailableCustomers() {
		List<Customer> customers = new ArrayList<Customer>();
		TypedQuery<Customer> query = em.createQuery("SELECT c FROM Customer c "
				+ "WHERE c NOT IN (SELECT a.customer FROM Account a WHERE a.user != null)", Customer.class);
		
		customers = query.getResultList();
		if (customers.size() > 0) {
			return customers;
		}
		return null;
	}
	
	/** 
	 * Update customer informations.
	 * @param customer
	 */
	@Transactional
	public void updateCustomer(Customer customer) {
		em.merge(customer);
	}
	
	/**
	 * Remove a customer from database.
	 * @param customer
	 */
	@Transactional
	public void deleteCustomer(Customer customer) {
		em.remove(customer);
	}
	
	/**
	 * Find weather a customer existed or not.
	 * @param customer
	 * @return
	 */
	@Transactional
	public Customer findCustomer(String customerCardNumberId) {
		TypedQuery<Customer> query = em.createQuery("SELECT c FROM Customer c where c.cardNumberId = :id", Customer.class);
		query.setParameter("id", customerCardNumberId);
		Customer customer = query.getSingleResult();
		return customer;
	}
}
